package com.ruoyi.api;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.appuser.domain.Appuser;
import com.ruoyi.appuser.domain.vo.AppuserTaskVo;
import com.ruoyi.appuser.service.IAppuserService;
import com.ruoyi.commodity.domain.Commodity;
import com.ruoyi.commodity.domain.CommodityOrder;
import com.ruoyi.commodity.domain.CommodityOrderSub;
import com.ruoyi.commodity.domain.vo.CommodityVo;
import com.ruoyi.commodity.domain.vo.ShopParams;
import com.ruoyi.commodity.service.ICommodityOrderService;
import com.ruoyi.commodity.service.ICommodityOrderSubService;
import com.ruoyi.commodity.service.ICommodityService;
import com.ruoyi.common.annotation.PassToken;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.integral.domain.Integral;
import com.ruoyi.integral.service.IIntegralService;
import com.ruoyi.locker.domain.Locker;
import com.ruoyi.locker.service.ILockerService;
import com.ruoyi.normal.domain.NormalTask;
import com.ruoyi.normal.domain.NormalTaskRecord;
import com.ruoyi.normal.service.INormalTaskRecordService;
import com.ruoyi.normal.service.INormalTaskService;
import com.ruoyi.season.domain.PlaySeason;
import com.ruoyi.season.domain.PlaySeasonCommonTask;
import com.ruoyi.season.domain.PlaySeasonRecord;
import com.ruoyi.season.domain.PlaySeasonTaskRecord;
import com.ruoyi.season.service.IPlaySeasonCommonTaskService;
import com.ruoyi.season.service.IPlaySeasonRecordService;
import com.ruoyi.season.service.IPlaySeasonService;
import com.ruoyi.season.service.IPlaySeasonTaskRecordService;
import com.ruoyi.util.AuthUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author admin
 */
@RestController
@RequestMapping("/app-api/shop")
@Api(value = "商城", tags = "移动端接口")
public class AppShopController  extends AppBaseController {
    @Resource
    private IAppuserService appuserService;
    @Resource
    private ILockerService lockerService;
    @Resource
    private ICommodityService commodityService;
    @Resource
    private ICommodityOrderService commodityOrderService;
    @Resource
    private ICommodityOrderSubService commodityOrderSubService;
    @Resource
    private IIntegralService integralService;
    @Resource
    private IPlaySeasonCommonTaskService playSeasonCommonTaskService;
    @Resource
    private IPlaySeasonRecordService playSeasonRecordService;

    @Resource
    private IPlaySeasonTaskRecordService playSeasonTaskRecordService;
    @Resource
    private IPlaySeasonService playSeasonService;



    @GetMapping("/list")
    @ApiOperation(value = "商品列表",notes = "classify 分类 1赛季商品2普通商品, pageNo起始页,pageSize页数")
    public R shopInfo(@RequestParam(name = "pageNo" ,defaultValue = "1") Integer pageNo
            , @RequestParam(name = "pageSize",defaultValue = "10") Integer pageSize,
                      @RequestParam(defaultValue = "1") Integer classify
    ) {
        String loginUserId = AuthUtil.getAppUserId();
        Appuser appuser = appuserService.getById(loginUserId);

        IPage<CommodityVo> page = new Page<CommodityVo>(pageNo,pageSize);
        List<CommodityVo> list = commodityService.selectShopInfo(page,classify);
         if(!CollectionUtils.isEmpty(list)){
              for(CommodityVo temp : list){
                  if(appuser.getIsVip() == 1){
                      temp.setShopIntegral(temp.getNormalIntegral());
                      temp.setShopPrice(temp.getPrice());
                  }else if(appuser.getIsVip() == 2){
                      temp.setShopIntegral(temp.getVipIntegral());
                      temp.setShopPrice(temp.getVipPrice());

                  }
              }

         }

        return R.ok(page.setRecords(list));
    }



    @GetMapping("/detail")
    @ApiOperation(value = "商品详情",notes = "commodityId商品id")
    public R detail(String commodityId) {
        if(StringUtils.isBlank(commodityId)){
               return R.fail("参数不为空");
        }
        String loginUserId = AuthUtil.getAppUserId();
        Appuser appuser = appuserService.getById(loginUserId);

        CommodityVo commodityVo = commodityService.selectShopInfoById(commodityId);
        if(Objects.nonNull(commodityVo)){
            if(appuser.getIsVip() == 1){
                commodityVo.setShopIntegral(commodityVo.getNormalIntegral());
                commodityVo.setShopPrice(commodityVo.getPrice());
            }else if(appuser.getIsVip() == 2){
                commodityVo.setShopIntegral(commodityVo.getVipIntegral());
                commodityVo.setShopPrice(commodityVo.getVipPrice());

            }
        }

        return R.ok(commodityVo);
    }



    @PostMapping("/shopPay")
    @ApiOperation(value = "商品支付",notes = "")
    @Transactional
    public R shopPay(ShopParams shopParams) {

        String commodityId = shopParams.getCommodityId();
        if(StringUtils.isBlank(commodityId)){
           return R.fail("商品id不为空");
        }
        BigDecimal paidAmount = shopParams.getPaidAmount();
        if(null == paidAmount){
            return R.fail("支付金额不为空");
        }
        Integer count = shopParams.getCount();
        if(null == count ){
            return R.fail("数量不为空");
        }

        BigDecimal singlePrice = shopParams.getSinglePrice();
        if(null == singlePrice ){
            return R.fail("单价不为空");
        }

        BigDecimal showIntegral = shopParams.getShowIntegral();
        if(null == showIntegral ){
           showIntegral = new BigDecimal(0);
        }

        String loginUserId = AuthUtil.getAppUserId();
        Appuser appuser = appuserService.getById(loginUserId);
        Commodity commodityInfo = commodityService.getById(commodityId);
        PlaySeason playSeason = new PlaySeason();
        if(StringUtils.isNotBlank(commodityInfo.getPlaySeasonId())){
             playSeason = playSeasonService.getById(commodityInfo.getPlaySeasonId());

        }

        if(commodityInfo.getStock().compareTo(count) == -1){
            return R.fail("库存不足");

        }
        Date date = new Date();
        CommodityOrder commodityOrder = new CommodityOrder();
        commodityOrder.setAppuserId(loginUserId);
        commodityOrder.setOid(createOrderNo("WX"));
        commodityOrder.setCreateTime(date);
        commodityOrder.setPaidPrice(paidAmount);
        commodityOrder.setTotalIntegral(showIntegral);
        commodityOrder.setCount(count);
        commodityOrder.setSinglePrice(singlePrice);
        commodityOrder.setStatus(1);
        commodityOrder.setTotalPrice(singlePrice.multiply(new BigDecimal(count)));

        if(!commodityOrderService.save(commodityOrder)){
            throw new RuntimeException("商品订单添加失败");
        }

        CommodityOrderSub commodityOrderSub = new CommodityOrderSub();
        commodityOrderSub.setCid(commodityId);
        commodityOrderSub.setFid(commodityOrder.getId());
        commodityOrderSub.setName(commodityInfo.getName());
        commodityOrderSub.setPicture(commodityInfo.getPicture());
        commodityOrderSub.setPrice(singlePrice);
        commodityOrderSub.setNumber(count);
        commodityOrderSub.setCreateTime(date);
        commodityOrderSub.setIntegral(showIntegral);
        commodityOrderSub.setSmallPrice(paidAmount);
        commodityOrderSub.setTotalPrice(singlePrice.multiply(new BigDecimal(count)));
        if(!commodityOrderSubService.save(commodityOrderSub)){
            throw new RuntimeException("商品子订单添加失败");

        }

        int stock = commodityInfo.getStock() - count;
        if(!commodityService.update(new LambdaUpdateWrapper<Commodity>()
                .set(Commodity:: getStock,stock)
                .eq(Commodity:: getId,commodityInfo.getId())
        )){
            throw new RuntimeException("更新商品库存失败");

        }

        BigDecimal afterShopIntegral = new BigDecimal(0);
        BigDecimal afterTaskIntegral = new BigDecimal(0);
        /**任务积分*/
        BigDecimal taskIntegral = new BigDecimal(0);

        /**当前用户赛季信息*/
        PlaySeasonRecord playInfo = playSeasonRecordService.getById(appuser.getPlaySeasonRecordId());
        PlaySeasonCommonTask taskInfo = playSeasonCommonTaskService
                .getOne(new LambdaQueryWrapper<PlaySeasonCommonTask>()
                        .eq(PlaySeasonCommonTask :: getType,2)
                        .eq(PlaySeasonCommonTask :: getIsDeleted,0)
                        .eq(PlaySeasonCommonTask :: getPlaySeasonId,playInfo.getPlaySeasonId())
                );

        /**查询当日购买商品任务是否完成*/
        Integer completedCounts =  playSeasonTaskRecordService.selectRecordCounts(loginUserId
                ,appuser.getPlaySeasonRecordId(),taskInfo.getId());

        if(completedCounts.compareTo(taskInfo.getCounts()) == -1
                && commodityId.equals(taskInfo.getProductId())){
            taskIntegral = taskInfo.getVipIntegral();

            /**更新任务记录*/
            PlaySeasonTaskRecord record = new PlaySeasonTaskRecord();
            record.setProductId(commodityInfo.getId());
            record.setCreateTime(date);
            record.setPlaySeasonRecordId(appuser.getPlaySeasonRecordId());
            record.setTaskId(taskInfo.getId());
            if(!playSeasonTaskRecordService.save(record)){
                throw new RuntimeException("任务记录更新失败");

            }
        }

        /**任务信息*/
        if(appuser.getIsVip() == 1){
            /**商品积分*/
            afterTaskIntegral = appuser.getNormalIntegral().add(taskIntegral);

            afterShopIntegral = appuser.getNormalIntegral().add(showIntegral);

            BigDecimal profit = afterShopIntegral.add(taskIntegral);
            if(!appuserService.update(new LambdaUpdateWrapper<Appuser>()
                    .set(Appuser::getNormalIntegral,profit)
                    .set(Appuser::getUpdateTime,date)
                    .eq(Appuser::getId,loginUserId)
            )){
                throw new RuntimeException("更新用户积分失败");

            }

        }else if(appuser.getIsVip() == 2){

            /**任务变化后积分*/
            afterTaskIntegral = appuser.getVipIntegral().add(taskIntegral);
            /**购买商品积分*/
            afterShopIntegral = appuser.getVipIntegral().add(showIntegral);
            BigDecimal profit = afterShopIntegral.add(taskIntegral);
            if(!appuserService.update(new LambdaUpdateWrapper<Appuser>()
                    .set(Appuser::getVipIntegral,profit)
                    .set(Appuser::getUpdateTime,date)
                    .eq(Appuser::getId,loginUserId)
            )){
                throw new RuntimeException("更新用户积分失败");

            }


        }

       if(taskIntegral.compareTo(new BigDecimal(0)) == 1){
           /**商品任务完成更新积分*/
           Integral task = new Integral();
           task.setContent(taskInfo.getName());
           task.setAppuserId(loginUserId);
           task.setBalance(afterTaskIntegral);
           task.setProfit(taskIntegral);
           task.setType(2);
           task.setCreateTime(date);
           if(!integralService.save(task)){
               throw new RuntimeException("积分记录失败");

           }
       }

        /**买商品更新积分*/
        Integral insertIntegral = new Integral();
        insertIntegral.setContent(commodityInfo.getName());
        insertIntegral.setAppuserId(loginUserId);
        insertIntegral.setBalance(afterShopIntegral);
        insertIntegral.setProfit(showIntegral);
        insertIntegral.setType(2);
        insertIntegral.setCreateTime(date);
        if(!integralService.save(insertIntegral)){
            throw new RuntimeException("积分记录失败");

        }

        /**更新存储柜*/
        Locker locker = new Locker();
        locker.setName(commodityInfo.getName());
        locker.setPicture(commodityInfo.getPicture());
        locker.setProductId(commodityInfo.getId());
        locker.setType(1);
        locker.setCount(count);
        locker.setCid(commodityOrder.getId());
        locker.setAppuserId(loginUserId);
        locker.setCreateTime(date);
        if(!lockerService.save(locker)){
            throw new RuntimeException("领取奖励失败");
        }
        if(commodityInfo.getClassify() == 1){
            /**更新存储柜*/
            Locker season = new Locker();
            if(Objects.nonNull(playSeason) && StringUtils.isNotBlank(playSeason.getId())){
                season.setName(playSeason.getName());
                season.setPicture(playSeason.getPicture());
            }

            season.setProductId(commodityInfo.getId());
            season.setPlaySeasonId(commodityInfo.getPlaySeasonId());
            season.setType(3);
            season.setCid(commodityOrder.getId());
            season.setAppuserId(loginUserId);
            season.setCreateTime(date);
            if(!lockerService.save(season)){
                throw new RuntimeException("储物柜获得赛季失败");

            }
        }
        return R.ok();
    }


}
